from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.http import HttpResponseRedirect, Http404
from django.contrib.auth.decorators import login_required
from django.core.paginator import ObjectPaginator, InvalidPage
from django.db.models import Q

from common.easyfeed import render_feed
from common.common import get_full_path
from bookmarks.models import Bookmark
from bookmarks.forms import BookmarkForm, BookmarkSearchForm
import feeds


def index(request):
  form = BookmarkSearchForm(initial={'q' : ''})
  latest_bookmark_list = ObjectPaginator(get_list_or_404(Bookmark), 25)
  return render_to_response('bookmarks/index.html', {'latest_bookmark_list': latest_bookmark_list.get_page(0), 'request':request, 'search' : form })


def search_bookmarks(request, user=None):

  if request.method == 'GET':
    query = request.GET.get('q','')

  elif request.method == 'POST':
    query = request.POST.get('q','')

  else:
    query = ''
    

  if query:
    if user:
      qset = (
        Q(user__username__exact=user) &
        (
          Q(title__icontains=query) |
          Q(tags__icontains=query) |
          Q(description__icontains=query) |
          Q(url__icontains=query) 
        )
      )
    else:
      qset = (
        Q(title__icontains=query) |
        Q(tags__icontains=query) |
        Q(user__username__icontains=query) |
        Q(description__icontains=query) |
        Q(url__icontains=query) 
      )

    form = BookmarkSearchForm(initial={'q' : query})
    
    results = Bookmark.objects.filter(qset).distinct()

  else:
    form = BookmarkSearchForm(initial={'q' : ''})
    results = []



  return render_to_response('bookmarks/search.html', { 'results' : results,
                                                       'query' : query,
                                                       'search' : form,
                                                       'request' : request,
                                                       'search_url' : request.path  })



def index_rss(request):
  return render_feed(feeds.LatestBookmarkFeed(get_full_path(request)))


def user_index(request, user, page = 1):

  form = BookmarkSearchForm(initial={'q' : ''})
  page = int(page)
  bookmarks = ObjectPaginator(get_list_or_404(Bookmark, user__username=user), 25)

  try:
    bookmark_list = bookmarks.get_page(page -1)
  except InvalidPage:
    raise Http404("That page does not exist. Go away.")


  return render_to_response('bookmarks/user_index.html', { 'bookmarks': bookmarks.get_page(page - 1),
                                                           'request' : request,
                                                           'results_per_page' : 25,
                                                           'is_paginated': bookmarks.pages > 1,
                                                           'has_next': bookmarks.has_next_page(page - 1),
                                                           'has_previous': bookmarks.has_previous_page(page - 1),
                                                           'last_on_page' : bookmarks.last_on_page(page - 1),
                                                           'first_on_page' : bookmarks.first_on_page(page - 1),
                                                           'pages' : bookmarks.pages,
                                                           'hits' : bookmarks.hits,
                                                           'page_range' : bookmarks.page_range,
                                                           'page': page,
                                                           'next' : page + 1,
                                                           'previous' : page - 1,
                                                           'list_url' : '/bookmarks/%s/' % user,
                                                           'search_url' : '/bookmarks/%s/search' % user,
                                                           'username' : user,
                                                           'search' : form })



def rss_bookmarks(request, user):
  return render_feed(feeds.AltFeed(get_full_path(request), user, paginate=True, paginate_by=50))

@login_required(redirect_field_name='r')
def export_bookmarks(request, user):
  return render_feed(feeds.AltFeed(get_full_path(request), request.user))



@login_required(redirect_field_name='r')
def add_bookmark(request, user):
  
  if request.method == 'POST' and str(user) == str(request.user):
    new_data = request.POST.copy()
    form = BookmarkForm(new_data, auto_id=True)

    if form.is_valid():
      bookmark = Bookmark(title = form.cleaned_data['title'],
                          description = form.cleaned_data['description'],
                          url = form.cleaned_data['url'],
                          tags = form.cleaned_data['tags'],
                          user = request.user)
      try:
        bookmark.save()
      except IntegrityError:
        pass

      return HttpResponseRedirect(form.cleaned_data['url'])
    else:
      title = request.POST.get('title', '')
      description = request.POST.get('description', '')
      url = request.POST.get('url', '')
      tags = request.POST.get('tags', '')

      form = BookmarkForm(initial={'title': title,
                                   'description': description,
                                   'url': url,
                                   'tags': tags })
  else:
    title = request.GET.get('title', '')
    description = request.GET.get('description', '')
    url = request.GET.get('url', '')
    tags = request.GET.get('tags', '')

    form = BookmarkForm(initial={'title': title,
                                 'description': description,
                                 'url': url,
                                 'tags': tags })
    
  return render_to_response('bookmarks/add_bookmark.html', { 'form': form, 'request': request })
